package com.briup.store.web.interceptor;

import com.briup.common.utils.JsonWebTokenUtils;
import com.briup.common.utils.UserContext;
import com.briup.store.config.AuthProperties;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class UserInfoInterceptor implements HandlerInterceptor {
    @Autowired
    private AuthProperties authProperties;

    private AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("request.getPath() = " + request.getRequestURI());
        // 2.判断是否不需要拦截
        if(isExclude(request.getRequestURI())){
            // 无需拦截，直接放行
            return true;
        }
        if ((request.getMethod().equals("POST") || request.getMethod().equals("OPTIONS"))
                && antPathMatcher.match(request.getRequestURI(), "/auths")) {
            return true;
        }
        //拿到jwt令牌
        String jwt = request.getHeader("Authorization");
        //声明Claims对象
        Claims claims = null;
        try {
            //解析令牌
            claims = JsonWebTokenUtils.parseJWT(jwt);
        } catch (Exception e) {
            request.setAttribute("exception", e);
            request.getRequestDispatcher("/exception").forward(request, response);
            return false;
//            throw new SystemException(CodeAndMessageEnum.JSON_WEB_TOKEN_INVALID);
        }

        //拿到用户ID
        Integer userId = Integer.parseInt((String) claims.get("sub"));
        //System.out.println("in interceptor,get sub, id: " + id);

        //添加用户id,本次请求-响应 一直有效
        UserContext.setUser(userId);

        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 移除用户
        UserContext.removeUser();
    }

    private boolean isExclude(String antPath) {
        for (String pathPattern : authProperties.getExcludePaths()) {
            if(antPathMatcher.match(pathPattern, antPath)){
                return true;
            }
        }
        return false;
    }

}
